package com.yn.xr.front.base.action;

import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.web.context.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;
import com.yn.xr.common.exception.NotLoginUserSessionInfoException;
import com.yn.xr.common.util.StringUtils;
import com.yn.xr.front.base.constants.SystemConstants;
import com.yn.xr.front.user.service.UserRegisterService;
import com.yn.xr.user.mode.UserRegister;

/**
 * 所有action基类
 * 
 * @description:
 * @fileName:BaseAction.java
 * @createTime:2014年10月29日 下午5:34:48
 * @author:Wuwenyong
 * @version 1.0.0
 * 
 */
public class BaseAction extends ActionSupport implements ServletRequestAware,
		ServletResponseAware, ServletContextAware, SessionAware {

	private static final long serialVersionUID = -7837488843688436544L;

	private static Logger logger = Logger.getLogger(BaseAction.class);

	public javax.servlet.http.HttpServletRequest request;

	public javax.servlet.http.HttpServletResponse response;

	public Map<String, Object> session;

	private ServletContext servletContext;

	public String random;

	public int pageNo = 1;

	public int pageSize = 10;

	private String view;// 动态视图

	@Resource
	private UserRegisterService userRegisterService;

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;

	}

	public Map<String, Object> getSession() {
		return session;
	}

	public ServletContext getServletContext() {
		return servletContext;
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	/**
	 * @function: 输出字符
	 * @param str
	 *            void
	 * @exception
	 * @author:Wuwenyong
	 * @since 1.0.0
	 */
	protected void outStr(String str) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(str);
		} catch (Exception e) {
		}
	}

	protected void printStr(String str) throws Exception {
		try {
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(str);
		} catch (Exception e) {
			throw e;
		}
	}

	public String getRandom() {
		return random;
	}

	public void setRandom(String random) {
		this.random = random;
	}

	public String getView() {
		return view;
	}

	public void setView(String view) {
		this.view = view;
	}

	/**
	 * 返回动态视图
	 * 
	 * @function:
	 * @param view
	 * @return String
	 * @exception
	 * @author:Wuwenyong
	 * @since 1.0.0
	 */
	public String toView(String view) throws Exception {
		this.view = view;
		return "view";

	}

	/**
	 * 获得登录用户
	 * 
	 * @function:
	 * @return UserRegister
	 * @exception
	 * @author:孙元宝
	 * @since 1.0.0
	 */
	public UserRegister getLoginUser() throws Exception {

		UserRegister user = null;
		if (this.request != null) {
			Object o = this.getSession().get(SystemConstants.USER_SESSION_INFO);
			if (o != null) {
				user = (UserRegister) o;
			}
		}
		return user;
	}

	/**
	 * 
	 * @function: 拿session 中的user id 再次查询用户
	 * @return
	 * @throws Exception
	 *             UserRegister
	 * @exception
	 * @author:孙元宝
	 * @since 1.0.0
	 */
	public UserRegister getNewLoginUser() throws Exception {

		UserRegister user = null;
		if (this.request != null) {
			Object o = this.getSession().get(SystemConstants.USER_SESSION_INFO);
			if (o != null) {
				user = (UserRegister) o;
				user = userRegisterService.getNewUsBySessionOb(user.getUserId());
			}
		}

		if (user == null) {
			throw new NotLoginUserSessionInfoException();
		}
		return user;
	}

	/**
	 * 
	 * description: 更新session
	 * 
	 * @param user
	 *            void
	 * @author:xiaozhen
	 * @since 1.0.0
	 */
	public void updateSessionUserInfo(UserRegister user) throws Exception {
		if (user != null) {
			UserRegister _user = getLoginUser();
			if (_user != null
					&& _user.getUserId().intValue() == user.getUserId()
							.intValue()) {
				this.getSession().remove(SystemConstants.USER_SESSION_INFO);
				getSession().put(SystemConstants.USER_SESSION_INFO, user);
			}
		}
	}

	/**
	 * 
	 * @function:删除session
	 * @return type void
	 * @exception
	 * @author:肖震
	 * @since 1.0.0
	 */
	public void deleteSessionUser() throws Exception {
		Object o = this.getSession().get(SystemConstants.USER_SESSION_INFO);
		if (o != null) {
			UserRegister user = (UserRegister) o;
			if (user != null) {
				if (user.getUserId() != null) {
					Object httpSessionObj = this.getSession().get(
							user.getUserId().toString());
					if (httpSessionObj != null) {
						this.getSession().remove(user.getUserId().toString());
					}
				}

				this.getSession().remove(SystemConstants.USER_SESSION_INFO);
			}
		}

	}

	public static void response(HttpServletResponse response, String msg,
			String type) throws Exception {
		response.setContentType(type);
		response.setCharacterEncoding("utf-8");
		try {
			response.getWriter().write(msg);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			logger.error("网络异常", e);
			throw e;
		}
	}

	public static String getIpAddr(HttpServletRequest request) {
		if (request == null)
			return "";

		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (!StringUtils.isEmpty(ip) && ip.contains(",")) {
			ip = ip.split(",")[0];
		}
		return ip;
	}

	// 格式化金额显示
	public String formatMoney(double s) {
		DecimalFormat fmt = new DecimalFormat(",##0.00"); // \u00A4##0.00
		fmt.setRoundingMode(RoundingMode.DOWN);
		return fmt.format(s);
	}

}
